<?php

namespace app\api\controller\timer;

use app\common\model\TaskQueueLog;
use think\Controller;

class Queue extends Controller
{
    //执行任务
    function excute()
    {
        $up = [];
        $model = new TaskQueueLog();
        $data = $model->data_list(['status' => 0, 'start_time' => ['<=', time()], 'try_count' => ['<=', 10]], 1, '*', 'id asc', 10);
        if ($data) {
            foreach ($data as $item) {
                $class = $item['class'];
                $method = $item['method'];
                if (!method_exists($class, $method) && !is_callable([$class, $method])) {
                    $up[] = [
                        'result' => '方法不存在或无法调用',
                        'status' => 1,
                        'try_count' => $item['try_count'] + 1,
                        'real_time' => time(),
                        'id' => $item['id']
                    ];
                    continue;
                }
                $item['param'] = json_decode($item['param'], true) ?? $item['param'];
                $reflection = new \ReflectionMethod($item['class'], $item['method']);
                if ($reflection->isStatic()) {
                    $res = $class::$method($item['param']);
                } else {
                    $res = (new $class())->$method($item['param']);
                }
                $up[] = [
                    'result' => is_array($res) ? json_encode($res, JSON_UNESCAPED_UNICODE) : $res,
                    'status' => 1,
                    'try_count' => $item['try_count'] + 1,
                    'real_time' => time(),
                    'id' => $item['id']
                ];

            }
            if ($up) {
                $model->isUpdate(true)->saveAll($up);
            }
        }

        data_return('操作完成', 0, ['count' => count($up)]);
    }
}